package com.security.springsecurity01.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@Configuration
public class RemverMeConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private DataSource dataSource;


    @Autowired
    private UserDetailsService myUserDetailsService;

    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
//设置数据源
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().loginPage("/login1.html")
                .loginProcessingUrl("/user/login")
                .defaultSuccessUrl("/main.html")
                .and().authorizeRequests()
                .antMatchers("/login1.html", "/error.html", "/user/login").permitAll()
                .anyRequest().authenticated();




        //记住我
        http.rememberMe()
                .tokenRepository(persistentTokenRepository())//设置持久化仓库
                .tokenValiditySeconds(3600) //超时时间,单位s 默认两周
                .userDetailsService(myUserDetailsService); //设置自定义登录逻辑
        http.csrf().disable();
    }
}
